package org.petstore.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class CodeServlet extends HttpServlet {
    public void  service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建空白图片
        BufferedImage image =new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
        //获取图片画笔
        Graphics g=image.getGraphics();
        Random r=new Random();
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //绘制矩形背景
        g.fillRect(0,0,100,30);
        //绘制20条干扰线
        for(int i=0;i<20;i++){
            g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
            g.drawLine(r.nextInt(100),r.nextInt(30),r.nextInt(100),r.nextInt(30));

        }
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //调用方法，获取长度为4的随机字符串
        String str1=getRanString(4);
        //将生成的验证码存在session里
        HttpSession session = request.getSession();
        session.setAttribute("code1",str1);
        g.setFont(new Font(null,Font.BOLD+Font.ITALIC,24));
        g.drawString(str1,15,25);

        //发送图片到客户端
        response.setContentType("image/jpeg");
        OutputStream out =response.getOutputStream();
        //将图片输入到页面展示
        ImageIO.write(image,"jpeg",out);
        out.close();
    }
    public String getRanString(int size){
        String str="ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        String number="";
        Random r=new Random();
        for(int i=0;i<size;i++){
            char c=str.charAt(r.nextInt(str.length()));
            number=number+c;
        }
        return number;
    }
}
